package com.chiaching.framwork.core.handler.security;

import com.alibaba.fastjson.JSONObject;
import com.chiaching.framwork.domian.bean.SuperMallUserDetail;
import com.chiaching.framwork.domian.constant.CoreConstant;
import com.chiaching.framwork.utils.CookieUtil;
import com.chiaching.framwork.utils.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author jiajing.he
 * @date 2021/7/27 下午2:53
 */
@Slf4j
public class SuperMallLoginSuccessHandler implements AuthenticationSuccessHandler {
    @Resource
    private RedisUtils redisUtils;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        if (authentication instanceof UsernamePasswordAuthenticationToken){
            UsernamePasswordAuthenticationToken authenticationToken = (UsernamePasswordAuthenticationToken) authentication;
            //UserDetailService返回值
            Object principal = authenticationToken.getPrincipal();
            log.info("SuperMallLoginSuccessHandler principal[{}]",principal);
            if (principal instanceof SuperMallUserDetail){
                SuperMallUserDetail superMallUserDetail= (SuperMallUserDetail)principal;
                String uuid = UUID.randomUUID().toString();
                int second = Long.valueOf(TimeUnit.DAYS.toSeconds(1)).intValue();
                redisUtils.setObject(uuid,superMallUserDetail,second);
                CookieUtil.addCookieToTopDomain(httpServletRequest, httpServletResponse, CoreConstant.USER_TOKEN,uuid ,second,true);
            }
        }
    }
}
